<template>
  <div class="bg-style">
    <i-pageBody class="add_i-color">
      <div slot="page-main">
        <div class="container container-space container-space--vertical">
          <div class="container-space__child">
            <Form ref="form" :model="formdata">
              <Row :gutter="20">
                <i-col :span="5">
                  <FormItem prop="area" label="事件区域：" :label-width="85">
                    <Cascader
                      ref="cascader"
                      :data="options.orgtrees"
                      v-model="formdata.area"
                      change-on-select
                    ></Cascader>
                  </FormItem>
                </i-col>
                <i-col :span="5">
                  <FormItem prop="statue" label="状态：" :label-width="60">
                    <Select
                      v-model="formdata.statue"
                      placeholder="请选择状态"
                      style="100%"
                      clearable
                    >
                      <Option
                        :value="value"
                        v-for="({ label, value }, index) in options.status"
                        :key="index"
                        >{{ label }}</Option
                      >
                    </Select>
                  </FormItem>
                </i-col>
                <i-col :span="5">
                  <FormItem prop="time" label="下发时间：" :label-width="85">
                    <Date-picker
                      style="width:100%"
                      type="datetime"
                      placeholder="选择下发时间"
                      v-model="formdata.time"
                      clearable
                    ></Date-picker>
                  </FormItem>
                </i-col>
                <i-col :span="5">
                  <Button
                    type="primary"
                    @click="handleSearch"
                    :loading="loading.search"
                  >
                    查询
                  </Button>
                  <Button
                    type="default"
                    @click="handleReset"
                    :loading="loading.reset"
                  >
                    重置
                  </Button>
                </i-col>
                <i-col :span="4" class="container-align--right">
                  <Button
                    type="success"
                    @click="handleExport"
                    :loading="loading.export"
                  >
                    导出
                  </Button>
                </i-col>
              </Row>
            </Form>
          </div>
          <div class="container-space__child">
            <Table
              :columns="columns"
              :data="nextData"
              border
              stripe
              :loading="tableLoading"
            ></Table>
          </div>
          <div class="container-space__child" v-show="nextData.length > 0">
            <div class="container-page">
              <PageHeader
                :total="formdata.total"
                :page-size="formdata.pageSize"
                :page="formdata.page"
              ></PageHeader>
              <Page
                :total="formdata.total"
                :page-size="formdata.pageSize"
                :current="formdata.page"
                @on-change="handlePage"
                show-sizer
                @on-page-size-change="handlePageSize"
              />
            </div>
          </div>
        </div>
      </div>
    </i-pageBody>
  </div>
</template>

<script>
import PageHeader from "../../components/page-header";
import { STATUS_OPTIONS, CHECK_OPTIONS, TABLE_COLUNMS } from "./constants";
import {
  getAlarmOrgtree,
  getEmergencyList,
  getCustomerList,
  getEquipList,
  addEmergency,
  updateEmergency,
  exportEmergency
} from "@/api/scada";
import moment from "moment";
function getTreeDataList(tree) {
  return tree.map((element) => {
    const { areaNo, areaName, children: prevChildren } = element;
    const children = getTreeDataList(prevChildren || []);
    return {
      value: areaNo,
      label: areaName,
      children
    };
  });
}
function getTreeNameById(treeId, treeList) {
  let hasFound = false;
  let result = "";
  function getValue(data) {
    if (Array.isArray(data) && !hasFound) {
      data.forEach((element) => {
        const { value, label, children } = element;
        if (treeId === value) {
          result = label || "";
          hasFound = true;
        } else if (children) {
          getValue(children);
        }
      });
    }
  }
  getValue(treeList);
  return result;
}

export default {
  name: "emergency",
  props: {},
  data() {
    const columns = [
      ...TABLE_COLUNMS,
      {
        title: "操作",
        width: 160,
        fixed: "right",
        align: "center",
        render: (h, params) => {
          const { row } = params;
          const { orderstate } = row;
          return h("span", [
            h(
              "Button",
              {
                props: {
                  type: "warning",
                  size: "small",
                  disabled: ["1", "2", "3"].includes(orderstate)
                },
                style: {
                  "margin-right": "8px"
                },
                nativeOn: {
                  click: () => {
                    this.handleDecompose(row);
                  }
                }
              },
              "分解"
            ),
            h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small",
                  ghost: true
                },
                nativeOn: {
                  click: () => {
                    this.handleCheck(row);
                  }
                }
              },
              "查看"
            )
          ]);
        }
      }
    ];
    return {
      loading: {
        normal: false,
        search: false,
        reset: false,
        page: false,
        export: false
      },
      options: {
        status: STATUS_OPTIONS,
        orgtrees: [],
        customers: [],
        equip: []
      },
      formdata: {
        area: [],
        statue: "",
        time: "",
        page: 1,
        pageSize: 10,
        total: 0
      },
      columns,
      data: []
    };
  },
  computed: {
    tableLoading() {
      const {
        loading: { normal, search, reset, page }
      } = this;
      return normal || search || reset || page;
    },
    nextData() {
      const { data } = this;
      return data.map((element) => {
        const { checkstate, orderstate } = element;
        const { label: checkLabel } =
          CHECK_OPTIONS.find((option) => option.value === checkstate) || {};
        const { label: orderLabel } =
          STATUS_OPTIONS.find((option) => option.value === orderstate) || {};
        return {
          ...element,
          orderLabel,
          checkLabel
        };
      });
    }
  },
  created() {},
  mounted() {
    this.getOrgtree();
    this.getEmergencyList();
  },
  watch: {},
  methods: {
    handleDecompose(row) {
      const { controlsid: controlsId, id, areaNo } = row;
      this.$router.push({
        name: "emergency-decompose",
        query: {
          controlsId,
          instructId: id,
          areaNo
        }
      });
    },
    handleCheck(row) {
      const { controlsid: controlsId } = row;
      this.$router.push({
        name: "emergency-check",
        query: {
          controlsId
        },
        params: { ...row }
      });
    },
    handleSearch() {
      this.formdata.page = 1;
      this.getEmergencyList("search");
    },
    handleReset() {
      this.formdata.page = 1;
      this.$refs.form.resetFields();
      this.getEmergencyList("reset");
    },
    handlePage(page) {
      this.formdata.page = page;
      this.getEmergencyList("page");
    },
    handlePageSize(pageSize) {
      this.formdata.pageSize = pageSize;
      this.getEmergencyList("page");
    },
    handleExport() {
      this.exportEmergency();
    },
    // 区域
    getOrgtree() {
      getAlarmOrgtree().then((ret) => {
        const { code, result } = ret || {};
        if (code === 200) {
          const nextResult = result ? [result] : [];
          this.options.orgtrees = getTreeDataList(nextResult);
        }
      });
    },
    getEmergencyList(loadingType = "normal") {
      this.loading[loadingType] = true;
      let {
        formdata: { area, statue, time, page: currentPage, pageSize }
      } = this;
      const areaNo = area[area.length - 1] || "";
      const areaName = getTreeNameById(areaNo, this.options.orgtrees);
      time = time ? moment(time).format("yyyy-MM-DD HH:mm:ss") : "";
      const params = {
        areaNo,
        statue,
        time,
        currentPage,
        pageSize
      };
      getEmergencyList(params)
        .then((ret) => {
          const { code, result } = ret || {};
          if (code === 200) {
            const { totalNum, custom } = result || {};
            const { data } = custom || {};
            this.formdata.total = totalNum || 0;
            this.data = data || [];
          }
        })
        .finally(() => {
          this.loading[loadingType] = false;
        });
    },
    exportEmergency() {
      this.loading.export = true;
      let {
        formdata: { area, statue, time }
      } = this;
      const areaNo = area[area.length - 1] || "";
      const areaName = getTreeNameById(areaNo, this.options.orgtrees);
      time = time ? moment(time).format("yyyy-MM-DD HH:mm:ss") : "";
      const params = {
        areaName,
        statue,
        time
      };
      exportEmergency(params, "arraybuffer")
        .then((ret) => {
          const blob = new Blob([ret], {
            type:
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          });
          this.downLoad(blob, "控制列表");
        })
        .finally(() => {
          this.loading.export = false;
        });
    },
    downLoad(blob, name) {
      const url = URL.createObjectURL(blob);
      let a = document.createElement("a");
      a.download = name;
      a.style.display = "none";
      a.href = url;
      document.body.appendChild(a);
      a.click();
      a.remove();
    }
  },
  components: { PageHeader }
};
</script>
<style scoped lang="scss">
.bg-style {
  width: 100%;
  height: 100%;
}
.container {
  padding: 20px;
  height: 100%;
  overflow: auto;
}
.container-title {
  padding-left: 10px;
  font-size: 16px;
  color: #333;
  position: relative;
}
.container-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #0893fd;
  line-height: 16px;
}

.container-space > .container-space__child:not(:last-child) {
  margin-right: 20px;
}
.container-space.container-space--vertical
  > .container-space__child:not(:last-child) {
  margin-bottom: 20px;
  margin-right: 0;
}
.container-space--inner {
  padding: 20px;
}

.container-align--center {
  text-align: center;
}
.container-align--right {
  text-align: right;
}
.container-page {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
<style>
.ivu-btn-ghost {
  color: #fff;
  background: transparent;
}
</style>
<style lang="scss" scoped>
/deep/ .ivu-table-tip table tr td {
  text-align: center;
  background-image: url("~@/assets/img/zwsj.png");
  background-position: center 60px;
  background-repeat: no-repeat;
  color: #999;
  height: 369px;
  background-size: 190px;
  span {
    display: none;
  }
}
</style>
